﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Tsingda.CacheModule
{
    public class ResponseFilter : Stream
    {
        #region 属性
        private StringBuilder sb;
        private Stream m_sink;
        private long m_position;
        private FileStream fs;
        private string filePath = string.Empty;
        public ResponseFilter(Stream sink, string key)
        {
            sb = new StringBuilder();
            this.m_sink = sink;
            this.filePath = key;
        }
        // The following members of Stream must be overriden.
        public override bool CanRead
        { get { return true; } }
        public override bool CanSeek
        { get { return false; } }
        public override bool CanWrite
        { get { return false; } }
        public override long Length
        { get { return 0; } }
        public override long Position
        {
            get { return m_position; }
            set { m_position = value; }
        }
        #endregion

        public override long Seek(long offset, System.IO.SeekOrigin direction)
        {
            return 0;
        }
        public override void SetLength(long length)
        {
            this.m_sink.SetLength(length);
        }
        public override void Close()
        {
            this.m_sink.Close();
            AddCache(this.filePath, sb.ToString());
        }
        public override void Flush()
        {
            this.m_sink.Flush();
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            return m_sink.Read(buffer, offset, count);
        }
        // Override the Write method to filter Response to a file.
        public override void Write(byte[] buffer, int offset, int count)
        {
            //首先判断有没有系统错误
            if (HttpContext.Current.Error == null)
            {
                sb.Append(Encoding.GetEncoding("utf-8").GetString(buffer));
            }
            //Write out the response to the browser.
            this.m_sink.Write(buffer, 0, count);
        }

        private void AddCache(string key, string memo)
        {
            CacheManage.Add(key, memo);
            sb = null;
        }
    }
}
